import React, { memo, useState, useCallback, useEffect } from "react";
import { Modal, Input } from "antd";
import { Timeline } from "antd";
import moment from "moment";
import { warning } from "./../../utils/message/message";
import { getListApi, addCommitApi } from "./api";

interface Item {
  comment: string;
  createdAt: string;
  userName?: string;
  createdByUser?: string;
  id: string;
}
interface OnSourceChage {
  (data: any[]): void;
}
interface IProps {
  visible: boolean;
  onCancel(): void;
  baseUrl: string;
  businessId: string;
  disabled?: boolean;
  inerSource?: any[];
  onSourceChage?: OnSourceChage;
}

const unmStyle = { color: '#0079FF' };

export default memo(({ visible, onCancel, disabled, onSourceChage, inerSource, businessId, baseUrl }: IProps) => {
  const [val, setVal] = useState("");
  const [dataSource, setDataSource] = useState<Item[]>([]);

  useEffect(() => {
    if (!businessId) return;
    if (inerSource) {
      return setDataSource(inerSource || []);
    }
    getListApi(baseUrl + "/find", businessId).then(setDataSource);
  }, [businessId, baseUrl]);

  const onChange = useCallback((e) => setVal(e.target.value), []);

  const _onOk = useCallback(async () => {
    if (!val) return warning("请填写备注信息");
    const newData = await addCommitApi(baseUrl + "/add", businessId, val);

    setVal('');
    setDataSource(dataSource.concat(newData));
    if (inerSource && onSourceChage) {
      onSourceChage(dataSource.concat(newData));
    }
  }, [val, baseUrl, dataSource]);

  return (
    <Modal destroyOnClose width={500} title="备注" visible={visible} onCancel={onCancel} onOk={_onOk}>
      <Timeline>
        {dataSource.map((item) => (
          <>
            <Timeline.Item>
              <p>{moment(item.createdAt).format(window.$app.MOMENT_FORMAT_TIME)}</p>
              <p style={unmStyle}> {item.userName || item.createdByUser}</p>
              <p> {item.comment}</p>
            </Timeline.Item>
          </>
        ))}
      </Timeline>
      <Input.TextArea disabled={disabled} onChange={onChange} value={val} placeholder="请填写备注信息" />
    </Modal>
  );
});
